package com.shushan.home;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.common.ui.UnScrollListView;
import com.android.common.ui.banner.Banner;
import com.android.common.ui.banner.BannerConfig;
import com.android.common.ui.banner.listener.OnBannerListener;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.android.permission.FloatPermissionUtil;
import com.android.permission.rom.RomType;
import com.android.permission.rom.RomUtils;
import com.android.refresh.RefreshHelper;
import com.android.refresh.RefreshView;
import com.shushan.accessibility.AccessibilityUtil;
import com.shushan.accessibility.OpenAccessiSettingHelper;
import com.shushan.permission.PermissionAccessibilityActivity;
import com.shushan.service.FlymeForegroundService;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.mixedexam.OralCalculateExamActivity;
import com.shushan.mixedexam.OralCalculateExerciseActivity;
import com.shushan.mixedexam.strangewords.StrangeWordsStudyActivity;
import com.shushan.pages.NewStudyWithExerciseActivity;
import com.shushan.pages.newtype.EnglishWordsExerciseActivity;
import com.shushan.pages.newtype.HearingExerciseActivity;
import com.shushan.pages.newtype.SpeakingExerciseActivity;
import com.shushan.pages.newtype.StrangeWordsExerciseActivity;
import com.shushan.util.StringTools;
import com.shushan.util.UmengEventUtil;
import com.shushan.versionupdate.entity.VersionUpdateConfig;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBeanDao;
import com.shushan.exam.ExamActivity;
import com.shushan.exercise.SyncExerciseActivity;
import com.shushan.home.adapter.AbsCommonAdapter;
import com.shushan.home.adapter.AwardTimeListAdapter;
import com.shushan.home.adapter.AwardToyListAdapter;
import com.shushan.home.adapter.StarMallRecyclerAdapter;
import com.shushan.home.adapter.SubjectRecyclerViewAdapter;
import com.shushan.home.bean.BannerDataBean;
import com.shushan.home.bean.LearnByDoBean;
import com.shushan.home.bean.MainDataBean;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.home.bean.RewardToyBean;
import com.shushan.home.bean.StarsDataBean;
import com.shushan.home.bean.UpdateBean;
import com.shushan.login.LoginOrRegisterActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.ExerciseRecordActivity;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.MyCollectionActivity;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.MyWrongTopicActivity;
import com.shushan.pages.OpenVipActivity;
import com.shushan.pages.SpecialTopicExerciseActivity;
import com.shushan.pages.SpecialTopicVideoActivity;
import com.shushan.pages.SubscriptionStepsActivity;
import com.shushan.pages.TimeAwardDetailsActivity;
import com.shushan.pages.ToyAwardDetailsActivity;
import com.shushan.pages.bean.MaketingActivityBean;
import com.shushan.pages.bean.MaketingDataBean;
import com.shushan.permission.PermissionMainActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.GridRecyclerDivider;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.DensityUtil;
import com.shushan.util.DeviceUtil;
import com.shushan.util.DialogUtil;
import com.shushan.util.GlideImageLoader;
import com.shushan.util.ImageUtils;
import com.shushan.util.OpenSettingUtils;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.web.BaseWebActivity;
import com.shushan.web.GoodsDetailWebActivity;
import com.shushan.web.ParentSetWebActivity;
import com.shushan.web.SetGuideWebActivity;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static com.android.permission.rom.RomType.COLOROS_ROM;

/**
 * @ClassName: MainActivity
 * @Desciption: //主页：我的练习
 * @author: zhangshihao
 * @date: 2018-04-03
 */
public class MainActivity extends BaseActivity implements View.OnClickListener
        , AdapterView.OnItemClickListener
        , AwardToyListAdapter.OnStartButtonClickListener
        , AwardTimeListAdapter.OnStartButtonClickListener2
        , OnFragmentItemClickListener,
        VerificationCodeView.OnCodeFinishListener, RefreshHelper {

    private static final String TAG = "MainActivity";

    private static final String TAB_TITLE_CHINEXE = "语文";
    private static final String TAB_TITLE_MATH = "数学";
    private static final String TAB_TITLE_ENGLISH = "英语";
    private String[] mTabTitleList = {TAB_TITLE_CHINEXE, TAB_TITLE_MATH, TAB_TITLE_ENGLISH};

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private LinearLayout llEmpty1;
    private LinearLayout llEmpty2;
    private UnScrollListView LvTimeAward;
    private UnScrollListView LvToyAward;
    private AwardTimeListAdapter timeAdapter;
    private AwardToyListAdapter toyAdapter;
    private ArrayList<SubjectFragment> fragmentList;

    private ImageView backImageView;
    private ImageView mTriangleDown;
    //抽屉上的元素
    private DrawerLayout mDrawerLayout;
    private RelativeLayout myCollection;
    private RelativeLayout myWrongTopic;
    private RelativeLayout mExerciseRecord;
    private RelativeLayout useNameLayout;
    private RelativeLayout parentSet;
    private RelativeLayout myStar;
    private TextView mlogout,tvOutApp;
    private TextView currentChildText;
    private ImageView ivHeadPortrait;
    private TextView tvLevelTerm;
    private RelativeLayout rlStarNum;
    private TextView tvStarNum;
    private RefreshView refreshView;

    private List<RewardToyBean> rewardToyBeans;
    private List<RewardTimeBean> rewardTimeBeans;
    private ArrayList<LearnByDoBean> chineseByDoList;
    private ArrayList<LearnByDoBean> mathByDoList;
    private ArrayList<LearnByDoBean> englishByDoList;
    private ArrayList<BannerDataBean> bannerDataBeanList;
    private ArrayList<StarsDataBean> starsDataBeanList;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private PopupWindow popupWindow;
    private ListView childListView;
    private Banner mBanner;
    private RelativeLayout rewardTimeTitleBar;
    private RelativeLayout rewardToyTitleBar;
    private RelativeLayout learnByDoTitleBar;
    private RelativeLayout starMallTitleBar;
    private RecyclerView rvStarMall;
    private CustomDialog permissionDialog;
    private Dialog gotoSetDialog;
    private Dialog vipTimeEndDialog;
    private CustomDialog floatDialog;

    private ChildChangeReceiver childChangeReceiver = null;
    private boolean isChildIdValid;
    private boolean isNotRewardSet = false;//孩子数据是否没设置完整
    private int clickType = 0;//点击类型 1:家长设置 2:回到桌面 3:退出登录

    private MaketingDataBean maketingDataBean;//分享营销数据bean
    private MaketingActivityBean maketingActivityBean;

    private final static int DELAY_TIMES = 1000*10;

    private Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    getLoopUserinfo();
                    break;
                case 1:
                    if(mHandler != null){
                        mHandler.sendEmptyMessageDelayed(1,500);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityStackManager.getActivityStackManager().popAllActivityWithOutCurrent();

        initWindow();

        setContentView(R.layout.activity_main);

        initView();

        getData(false);

        getMaketingData();

        registerBroadcastReceiver();

        getUpdate();

        mHandler.sendEmptyMessageDelayed(0,500);

        RomType romType = RomUtils.getRomType(this);
        if(romType == COLOROS_ROM && mHandler != null){

            mHandler.sendEmptyMessageDelayed(1,500);
        }

        if(romType == RomType.FLYME_ROM){
            startService(new Intent(this, FlymeForegroundService.class));
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        if(!(ToolUtils.isListEmpty(rewardTimeBeans) && ToolUtils.isListEmpty(rewardToyBeans))
                && !ToolUtils.hasSmartExercise(rewardToyBeans,rewardTimeBeans)){
            getData(false);
        }

        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        if(currentChildBean != null){
            currentChildText.setText(currentChildBean.childName);
            tvStarNum.setText(currentChildBean.stars + "");
            if(!TextUtils.isEmpty(currentChildBean.childAvatar)) {
                ivHeadPortrait.setVisibility(View.VISIBLE);
                ImageUtils.loadWXImageView(this, currentChildBean.childAvatar, ivHeadPortrait);
            }
            tvLevelTerm.setText(ToolUtils.getChildGradeStr(currentChildBean));
        }

        Object obj = Session.getSession().get("first_time");
        if(obj != null && (((int)obj) == 1)){
                DialogUtil.showFirstTimeLoginDialog(this);
        }else if(!shuShanApplication.isChildNotSet(isNotRewardSet) && shuShanApplication.isVip()){
            boolean permissionHasSet = SharedPreferencesUtils.getBooleanDate(Constants.MAIN_PERMISSION_HAS_SET_SHAREPREFERS_KEY);
            if(!permissionHasSet){
                showGotoPermissionDialog();
//                showGotoAccessibilityDialog();
            }
        }else if (shuShanApplication.isChildNotSet(isNotRewardSet)){

            showGotoSetDialog();
        }else if (!FloatPermissionUtil.checkPermission(this)){
            showFloatDialog();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(childChangeReceiver != null){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(childChangeReceiver);
        }
        mBanner.stopAutoPlay();

        mHandler.removeMessages(0);
        mHandler = null;

        if(permissionDialog != null){
            permissionDialog.dismiss();
        }

        if(gotoSetDialog != null){
            gotoSetDialog.dismiss();
        }

        if(vipTimeEndDialog != null){
            vipTimeEndDialog.dismiss();
        }

        if(floatDialog != null){
            floatDialog.dismiss();
        }
    }

    private void initWindow() {
        ScreenManager screenManager = ScreenManager.getInstance();
        screenManager.setStatusBar(true, this);
        screenManager.setScreenRoate(true, this);
        screenManager.setFullScreen(false, this);
    }

    private void initView() {
        refreshView = findViewById(R.id.main_refv);
        refreshView.setRefreshHelper(this);
        useNameLayout = findViewById(R.id.rl_user_name);
        mTabLayout = findViewById(R.id.tablayout);
        mViewPager = findViewById(R.id.tab_viewpager);
        llEmpty1 = findViewById(R.id.ll_empty_1);
        llEmpty2 = findViewById(R.id.ll_empty_2);
        LvTimeAward = findViewById(R.id.lv_time_award);
        LvToyAward = findViewById(R.id.lv_toy_award);
        mBanner = findViewById(R.id.banner);
        rewardTimeTitleBar = findViewById(R.id.rl_title_bar_1);
        rewardToyTitleBar = findViewById(R.id.rl_title_bar_2);
        learnByDoTitleBar = findViewById(R.id.rl_title_bar_3);
        starMallTitleBar = findViewById(R.id.rl_title_bar_4);

        backImageView = findViewById(R.id.actionbar_left_back_img);
        backImageView.setOnClickListener(this);
        mDrawerLayout = findViewById(R.id.drawer_layout_main);
        //允许抽屉滑出
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

        myCollection = findViewById(R.id.rl_list_my_collection);
        myWrongTopic = findViewById(R.id.rl_list_my_wrong_topic);
        mExerciseRecord = findViewById(R.id.rl_list_exercise_record);
        mlogout = findViewById(R.id.tv_logout);
        tvOutApp = findViewById(R.id.tv_out_app);
        ivHeadPortrait = findViewById(R.id.iv_head_portrait);
        mTriangleDown = findViewById(R.id.iv_triangle);
        currentChildText = findViewById(R.id.tv_user_name);
        tvLevelTerm = findViewById(R.id.tv_level_term);
        rlStarNum = findViewById(R.id.rl_star_num);
        tvStarNum = findViewById(R.id.tv_star_num);
        rvStarMall = findViewById(R.id.rv_star_mall);
        parentSet = findViewById(R.id.rl_list_parent_set);
        myStar = findViewById(R.id.rl_list_my_star);

        myStar.setOnClickListener(this);
        parentSet.setOnClickListener(this);
        rlStarNum.setOnClickListener(this);

        myCollection.setOnClickListener(this);
        myWrongTopic.setOnClickListener(this);
        mExerciseRecord.setOnClickListener(this);
        mlogout.setOnClickListener(this);
        tvOutApp.setOnClickListener(this);
        useNameLayout.setOnClickListener(this);

        //初始化广告栏
        initBanner();
        //初始化学贝商城列表
        rvStarMall.addItemDecoration(new GridRecyclerDivider(2, DensityUtil.dip2px(this,10)));
        rvStarMall.setLayoutManager(new GridLayoutManager(this,2));
    }

    private void initBanner(){
        mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR).setImageLoader(new GlideImageLoader());
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                    return;
                }else if(!shuShanApplication.isVip()) {
                    if(maketingActivityBean != null) {
                        DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
                    }
                }else if(ToolUtils.isListEmpty(bannerDataBeanList)){
                    return;
                }else{
                    BannerDataBean dataBean = bannerDataBeanList.get(position);
                    bannerJump(dataBean);
                }
            }
        });
    }

    //根据type跳转不同界面
    private void bannerJump(BannerDataBean dataBean){
        switch (dataBean.type){
            case 0://跳转H5
                Intent intent2 = new Intent(this, BaseWebActivity.class);
                intent2.putExtra("title",dataBean.name);
                intent2.putExtra("url",dataBean.url);
                startActivityAllow(intent2);
                break;
            case 1://跳转APP页面
                if(dataBean.url.equals("0")){
                    Session.getSession().put("maketingDataBean",maketingDataBean);

                    startActivity(InviteForFreeUseActivity.class);
                }
                break;
            case 2://跳转视频页面
                Intent intent = new Intent(this,SpecialTopicVideoActivity.class);
                intent.putExtra("isOnlyPlay",true);
                intent.putExtra("video_title",dataBean.name);
                intent.putExtra("video_url",dataBean.url);
                startActivityAllow(intent);
                break;
            default:
                break;
        }
    }

    //玩具奖励
    @Override
    public void onStartButtonClick(View itemView, int position) {
        if(shuShanApplication.isChildNotSet(isNotRewardSet)){
            showGotoSetDialog();
            return;
        }

        if(!shuShanApplication.isVip()){
            if(maketingActivityBean != null) {
                DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
            }
            return;
        }

        RewardToyBean rewardToyBean = rewardToyBeans.get(position);
        switch (rewardToyBean.practice_type) {
            case Constants.TYPE_SMART_EXERCISE:
                startSmartExam(rewardToyBean);
                break;
            case Constants.TYPE_SYNC_EXERCISE:
                Session.getSession().put("rewardToyBean",rewardToyBean);
                Intent intent = new Intent(this,SyncExerciseActivity.class);
                intent.putExtra("awardType", 2);
                startActivityAllow(intent);
                break;
            case Constants.TYPE_KEY_POINT_EXERCISE:
            case Constants.TYPE_DIFFICULT_POINT_EXERCISE:
            case Constants.TYPE_EASY_WRONG_EXERCISE:
            case Constants.TYPE_SPECIAL_TOPIC_EXERCISE:
                Session.getSession().put("rewardToyBean",rewardToyBean);
                Intent intent1 = new Intent(this,SpecialTopicExerciseActivity.class);
                intent1.putExtra("awardType", 2);
                startActivityAllow(intent1);
                break;
            default:
                break;
        }
    }

    //时间奖励
    @Override
    public void onStartButtonClick2(View itemView, int position) {
        if(shuShanApplication.isChildNotSet(isNotRewardSet)){
            showGotoSetDialog();
            return;
        }

        if(!shuShanApplication.isVip()){
            if(maketingActivityBean != null) {
                DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
            }
            return;
        }
        RewardTimeBean rewardTimeBean = rewardTimeBeans.get(position);
        switch (rewardTimeBean.practice_type) {
            case Constants.TYPE_SMART_EXERCISE:
                startSmartExam(rewardTimeBean);
                break;
            case Constants.TYPE_SYNC_EXERCISE:
                Session.getSession().put("rewardTimeBean",rewardTimeBean);

                Intent intent = new Intent(this, SyncExerciseActivity.class);
                intent.putExtra("awardType", 1);
                startActivityAllow(intent);
                break;
            case Constants.TYPE_KEY_POINT_EXERCISE:
            case Constants.TYPE_DIFFICULT_POINT_EXERCISE:
            case Constants.TYPE_EASY_WRONG_EXERCISE:
            case Constants.TYPE_SPECIAL_TOPIC_EXERCISE:
                Session.getSession().put("rewardTimeBean",rewardTimeBean);

                Intent intent1 = new Intent(this, SpecialTopicExerciseActivity.class);
                intent1.putExtra("awardType", 1);
                startActivityAllow(intent1);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.student_change_popup_lv:
                setChild(position);
                break;
            case R.id.lv_time_award:
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                    break;
                }

                if(!shuShanApplication.isVip()){
                    if(maketingActivityBean != null) {
                        DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
                    }
                    break;
                }
                RewardTimeBean rewardTimeBean = rewardTimeBeans.get(position);
                Session.getSession().put("rewardTimeBean",rewardTimeBean);

                startActivity(TimeAwardDetailsActivity.class);
                break;
            case R.id.lv_toy_award:
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                    break;
                }

                if(!shuShanApplication.isVip()){
                    if(maketingActivityBean != null) {
                        DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
                    }
                    break;
                }
                RewardToyBean rewardToyBean = rewardToyBeans.get(position);
                Session.getSession().put("rewardToyBean",rewardToyBean);

                startActivity(ToyAwardDetailsActivity.class);
                break;
            default:
                break;
        }
    }

    private void setChild(int position) {
        ChildBean selectBean = shuShanApplication.getChildBeanList().get(position);

        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        if(currentChildBean.id != selectBean.id){
            shuShanApplication.setCurrentChildBean(selectBean);
            currentChildText.setText(selectBean.childName);
            tvStarNum.setText(selectBean.stars + "");

            if(!TextUtils.isEmpty(selectBean.childAvatar)) {
                ivHeadPortrait.setVisibility(View.VISIBLE);
                ImageUtils.loadWXImageView(this, selectBean.childAvatar, ivHeadPortrait);
            }
            tvLevelTerm.setText(ToolUtils.getChildGradeStr(selectBean));

            getData(false);
        }

        if(popupWindow != null){
            popupWindow.dismiss();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_fork:
                if(gotoSetDialog != null){
                    gotoSetDialog.dismiss();
                }
                break;
            case R.id.btn_go_right_now:
                startActivity(SubscriptionStepsActivity.class);
                DialogUtil.dismissDialog();
                break;
            case R.id.btn_quick_set:
                //跳转到快速设置网页
                gotoGuideSet();
                DialogUtil.dismissDialog();
                break;
            case R.id.rl_star_num:
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                }else if(!shuShanApplication.isVip()) {
                    DialogUtil.showVIPpurchaseDialog(MainActivity.this,MainActivity.this,maketingActivityBean);
                }else {
                    closeDrawer();
                    startActivity(MyStarActivity.class);
                }
                break;
            case R.id.actionbar_left_back_img:
                openDrawer();
                break;
            case R.id.rl_list_parent_set://家长设置
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                }else if(!shuShanApplication.isVip()) {
                    DialogUtil.showVIPpurchaseDialog(MainActivity.this,MainActivity.this,maketingActivityBean);
                }else {
                    clickType = 1;
//                    DialogUtil.showInputParentPswDialog(this, this, this);
                    closeDrawer();
                }
                break;
            case R.id.rl_list_my_star://我的学贝
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                }else if(!shuShanApplication.isVip()) {
                    DialogUtil.showVIPpurchaseDialog(MainActivity.this,MainActivity.this,maketingActivityBean);
                }else {
                    startActivity(MyStarActivity.class);
                    closeDrawer();
                }
                break;
            case R.id.rl_list_my_collection:
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                    return;
                }
                if(!shuShanApplication.isVip()){
                    if(maketingActivityBean != null) {
                        DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
                        return;
                    }
                }
                closeDrawer();
                startActivity(MyCollectionActivity.class);
                break;
            case R.id.rl_list_my_wrong_topic:
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                    return;
                }
                if(!shuShanApplication.isVip()){
                    if(maketingActivityBean != null) {
                        DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
                        return;
                    }
                }
                closeDrawer();
                startActivity(MyWrongTopicActivity.class);
                break;
            case R.id.rl_list_exercise_record:
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                    return;
                }
                if(!shuShanApplication.isVip()){
                    if(maketingActivityBean != null) {
                        DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
                        return;
                    }
                }
                closeDrawer();
                startActivity(ExerciseRecordActivity.class);
                break;
            case R.id.tv_logout:
                logout();
                break;
            case R.id.tv_out_app://退出APP
                if(TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
                    ActivityStackManager.getActivityStackManager().popAllActivity();
                    return;
                }
                clickType = 2;
                DialogUtil.showParentOutAppDialog(this,this,this);
                closeDrawer();
                break;
            case R.id.rl_user_name:
                showPopupWindow();
                break;
            case R.id.iv_yellow_close://vip purchase dialog element
                DialogUtil.dismissDialog();
                break;
            case R.id.ll_open_vip://vip purchase dialog element
                Session.getSession().put("maketingDataBean",maketingDataBean);

                startActivity(OpenVipActivity.class);
                DialogUtil.dismissDialog();
                break;
            case R.id.ll_free_use://vip purchase dialog element
                Session.getSession().put("maketingDataBean",maketingDataBean);

                startActivity(InviteForFreeUseActivity.class);
                DialogUtil.dismissDialog();
                break;
            case R.id.rl_btn_buy_vip:
                Session.getSession().put("maketingDataBean",maketingDataBean);
                startActivity(OpenVipActivity.class);
                if(vipTimeEndDialog != null){
                    vipTimeEndDialog.dismiss();
                }
                break;
            case R.id.rl_btn_invite:
                Session.getSession().put("maketingDataBean",maketingDataBean);
                startActivity(InviteForFreeUseActivity.class);
                if(vipTimeEndDialog != null){
                    vipTimeEndDialog.dismiss();
                }
                break;
            case R.id.btn_find_back_psw://家长设置dialog：找回密码
                DialogUtil.showForgetPswDialog(this,this);
                break;
            case R.id.btn_cancel://家长设置dialog：取消
                DialogUtil.dismissParentSetDialog();
                break;
            case R.id.iv_close_no_bg://忘记密码dialog：×
                DialogUtil.dismissDialog();
                break;
            case R.id.iv_client_phone_num://忘记密码dialog：客服电话
                try {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants.CLIENT_PHONE_NUM));
                    startActivityAllow(intent);
                    DialogUtil.dismissDialog();
                    DialogUtil.dismissParentSetDialog();
                }catch (SecurityException se){
                    showToast("没有打电话权限");
                    Log.i(TAG,se.toString());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            Log.i(TAG,"clickType=" + clickType);
            if(clickType == 1){
                gotoParentSetWeb();
            }else if(clickType == 2){
                setAllowBack(true);
                ActivityStackManager.getActivityStackManager().popAllActivity();
            }else if (clickType == 3){
                final PushAgent mPushAgent = PushAgent.getInstance(this);
                int currentChildId = shuShanApplication.getCurrentChildId();
                if(currentChildId > 0){
                    mPushAgent.deleteAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                        }
                    });
                }

                int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
                if(useId > 0){
                    mPushAgent.deleteAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                        }
                    });
                }

                startActivity(LoginOrRegisterActivity.class);
                onBackAction();
                SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
            }

            DialogUtil.dismissParentSetDialog();
        }else{
            showToast("家长密码错误");
        }
    }

    private void gotoParentSetWeb(){
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.PARENT_SET)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        Intent intent = new Intent(this, ParentSetWebActivity.class);
        intent.putExtra("title","家长设置");
        intent.putExtra("url",urlParse.toString());
        startActivityForResultAllow(intent);
    }

    private void gotoGuideSet() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.DIST_SIMPLE_HTML)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("childid", (childId > 0) ? (childId+"") : "");

        Intent intent = new Intent(this, SetGuideWebActivity.class);
        intent.putExtra("title","快速设置");
        intent.putExtra("url",urlParse.toString());
        startActivityForResultAllow(intent);
    }

    private void showPopupWindow() {
        final int childId = shuShanApplication.getCurrentChildId();
        List<ChildBean> childBeanList = shuShanApplication.getChildBeanList();
        if(childBeanList == null || childBeanList.size() == 0){
            return;
        }

        View view = View.inflate(this, R.layout.student_change_popup_window, null);
        childListView = view.findViewById(R.id.student_change_popup_lv);
        popupWindow = new PopupWindow(view, 200, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

        AbsCommonAdapter<ChildBean> studentsAdapter = new AbsCommonAdapter<ChildBean>(this,R.layout.student_set_list_item,childBeanList) {

            @Override
            public void convert(ViewHolder helper,final ChildBean item, int selectedItem) {
                helper.setText(R.id.student_set_list_tv,item.childName);
                if(childId == item.id){
                    ((TextView)helper.getView(R.id.student_set_list_tv))
                            .setTextColor(getResources().getColor(R.color.blue_text_color));
                }else {
                    ((TextView)helper.getView(R.id.student_set_list_tv))
                            .setTextColor(getResources().getColor(R.color.deep_black_text_color));
                }
            }
        };

        childListView.setAdapter(studentsAdapter);
        childListView.setOnItemClickListener(this);

        popupWindow.showAsDropDown(mTriangleDown, 0, 20);
    }

    private ArrayList<SubjectFragment> fillFragments() {
        fragmentList = new ArrayList<SubjectFragment>();

        SubjectFragment chineseFragment = new SubjectFragment();
        Bundle data1 = new Bundle();

        data1.putParcelableArrayList("learnByDoBeanList", chineseByDoList);
        data1.putInt("subjectId",Constants.SUBJECT_CHINESE_ID);
        chineseFragment.setArguments(data1);
        chineseFragment.setOnFragmentItemClickListener(this);
        fragmentList.add(chineseFragment);

        SubjectFragment mathFragment = new SubjectFragment();
        Bundle data2 = new Bundle();
        data2.putParcelableArrayList("learnByDoBeanList", mathByDoList);
        data2.putInt("subjectId",Constants.SUBJECT_MACH_ID);
        mathFragment.setArguments(data2);
        mathFragment.setOnFragmentItemClickListener(this);
        fragmentList.add(mathFragment);

        SubjectFragment englishFragment = new SubjectFragment();
        Bundle data3 = new Bundle();
        data3.putParcelableArrayList("learnByDoBeanList", englishByDoList);
        data3.putInt("subjectId",Constants.SUBJECT_ENGLISH_ID);
        englishFragment.setArguments(data3);
        englishFragment.setOnFragmentItemClickListener(this);
        fragmentList.add(englishFragment);

        return fragmentList;
    }

    private void openDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    private void closeDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawers();
        }
    }

    @Override
    public void onDataRefresh() {
        getData(true);
    }

    class MyViewPagerAdapter extends FragmentStatePagerAdapter {

        private List<SubjectFragment> mFragmentList;
        private FragmentManager fm;

        public void setFragments(ArrayList<SubjectFragment> fragments) {
            if (this.mFragmentList != null) {
                FragmentTransaction ft = fm.beginTransaction();
                for (Fragment f : this.mFragmentList) {
                    ft.remove(f);
                }
                ft.commit();
                ft = null;
                fm.executePendingTransactions();
            }
            this.mFragmentList = fragments;
            notifyDataSetChanged();
        }

        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
            this.fm = fm;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return -1;//没有找到child要求重新加载
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTabTitleList[position];
        }
    }

    private void getData(final boolean isRefresh) {
        int childId = shuShanApplication.getCurrentChildId();
        if(childId <= 0) {//没有小孩
            isChildIdValid = false;
            showGotoSetDialog();
        }else{
            isChildIdValid = true;
            if(!isRefresh){
                showWaitDialog();
            }

        }

        UrlParse urlParse = new UrlCommParse(this,UrlConst.BASE_URL).appendRegion(UrlConst.MAIN_INDEX);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", (childId > 0) ? (childId+"") : "");

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MainDataBean>() {

                    @Override
                    protected void onCommon() {
                        Log.i(TAG,"onCommon isChildIdValid=" + isChildIdValid);
                        if(isChildIdValid && !isRefresh) {
                            dismissWaitDialog();
                        }

                        if (isRefresh){
                            refreshView.onCompleteRefresh();
                        }
                    }

                    @Override
                    protected void onSuccess(MainDataBean mainDataBean) {

                        if (mainDataBean.isEmpty()) {
                            isNotRewardSet = true;

                            hideLBDList();
                            hideRewardTime();
                            hideRewardToy();
                            showGotoSetDialog();
                        }else {
                            isNotRewardSet = false;
                        }

                        chineseByDoList = (ArrayList<LearnByDoBean>) mainDataBean.getChineseByDoList();
                        mathByDoList = (ArrayList<LearnByDoBean>) mainDataBean.getMathByDoList();
                        englishByDoList = (ArrayList<LearnByDoBean>) mainDataBean.getEnglishByDoList();

                        if(ToolUtils.isListEmpty(chineseByDoList) && ToolUtils.isListEmpty(mathByDoList) && ToolUtils.isListEmpty(englishByDoList)){
                            hideLBDList();
                        }else{
                            learnByDoTitleBar.setVisibility(View.VISIBLE);
                            mTabLayout.setVisibility(View.VISIBLE);
                            mViewPager.setVisibility(View.VISIBLE);
                            showSubjectFragments();
                        }

                        rewardTimeBeans = mainDataBean.getRewardTimeList();
                        rewardToyBeans = mainDataBean.getRewardToyList();

                        if (!ToolUtils.isListEmpty(rewardTimeBeans)) {
                            llEmpty1.setVisibility(View.GONE);
                            LvTimeAward.setVisibility(View.VISIBLE);
                            rewardTimeTitleBar.setVisibility(View.VISIBLE);
                            timeAdapter = new AwardTimeListAdapter(MainActivity.this, rewardTimeBeans);
                            timeAdapter.setOnStartButtonClickListener(MainActivity.this);
                            LvTimeAward.setOnItemClickListener(MainActivity.this);
                            LvTimeAward.setAdapter(timeAdapter);
                        } else {
                            hideRewardTime();
                        }
                        if (!ToolUtils.isListEmpty(rewardToyBeans)) {
                            llEmpty2.setVisibility(View.GONE);
                            LvToyAward.setVisibility(View.VISIBLE);
                            rewardToyTitleBar.setVisibility(View.VISIBLE);
                            toyAdapter = new AwardToyListAdapter(MainActivity.this, rewardToyBeans);
                            toyAdapter.setOnStartButtonClickListener(MainActivity.this);
                            LvToyAward.setOnItemClickListener(MainActivity.this);
                            LvToyAward.setAdapter(toyAdapter);
                        } else {
                            hideRewardToy();
                        }

                        bannerDataBeanList = (ArrayList<BannerDataBean>) mainDataBean.getBannerDataBeanList();
                        setBanner();

                        starsDataBeanList = (ArrayList<StarsDataBean>) mainDataBean.getStarsDataBeanList();
                        if(ToolUtils.isListEmpty(starsDataBeanList)){
                            hideStarGoodList();
                        }else{
                            setStarsGoodList(starsDataBeanList);
                        }


                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        clearMainData();

                        showSubjectFragments();

                        hideRewardTime();
                        hideRewardToy();

                        if(netRetBean.getServerCode() == 300){
                            showNoMsgError(netRetBean);

                            showGotoSetDialog();
                        }else {
                            showNetError(netRetBean);
                        }
                    }
                });
    }

    private void getMaketingData(){
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MEMBER_CENTER);
        UrlParse paramParse = new UrlCommParse(this).putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MaketingDataBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MaketingDataBean maketingDataBean) {
                        MainActivity.this.maketingDataBean = maketingDataBean;
                        MainActivity.this.maketingActivityBean = maketingDataBean.getMaketingActivityBeanList().get(0);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setBanner(){
        if(ToolUtils.isListEmpty(bannerDataBeanList)){
            Log.d(TAG,"banner数据为空");
            return;
        }
        List<String> images = new ArrayList<>();
        for(BannerDataBean bean : bannerDataBeanList){
            images.add(bean.pic);
        }
        mBanner.setImages(images).start();
    }

    private void setStarsGoodList(final List<StarsDataBean> starsDataBeans){
        StarMallRecyclerAdapter smRecyclerAdapter = new StarMallRecyclerAdapter(this,starsDataBeans);
        smRecyclerAdapter.setOnItemClickListener(new StarMallRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if(shuShanApplication.isChildNotSet(isNotRewardSet)){
                    showGotoSetDialog();
                }else if(!shuShanApplication.isVip()) {
                    DialogUtil.showVIPpurchaseDialog(MainActivity.this,MainActivity.this,maketingActivityBean);
                }else {
                    gotoGoodsWebDetail(starsDataBeans.get(position));
                }
            }
        });
        rvStarMall.setAdapter(smRecyclerAdapter);
    }

    private void hideStarGoodList(){
        starMallTitleBar.setVisibility(View.GONE);
        rvStarMall.setVisibility(View.GONE);
    }

    private void hideRewardTime(){
        rewardTimeTitleBar.setVisibility(View.GONE);
        llEmpty1.setVisibility(View.GONE);
        LvTimeAward.setVisibility(View.GONE);
    }

    private void hideRewardToy(){
        rewardToyTitleBar.setVisibility(View.GONE);
        llEmpty2.setVisibility(View.GONE);
        LvToyAward.setVisibility(View.GONE);
    }

    private void hideLBDList(){
        learnByDoTitleBar.setVisibility(View.GONE);
        mTabLayout.setupWithViewPager(null);
        mTabLayout.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
    }

    private void showSubjectFragments(){
        Log.i(TAG,"showSubjectFragments");

        MyViewPagerAdapter pagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        pagerAdapter.setFragments(fillFragments());
        mViewPager.setAdapter(pagerAdapter);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        //将ViewPager和TabLayout绑定
        mTabLayout.setupWithViewPager(mViewPager);
        setIndicator(mTabLayout,33,33);
    }

    private void startSmartExam(RewardToyBean rewardToyBean) {
        if(rewardToyBean == null){
            showToast("智能练习玩具奖励信息为空");
            return;
        }

        if(!rewardToyBean.znlx){
            showToast("智能练习暂无题目");
            return;
        }

        Session.getSession().put("rewardToyBean",rewardToyBean);

        Intent intent = new Intent(this,ExamActivity.class);
        intent.putExtra("awardType",2);
        startActivityAllow(intent);
    }

    private void startSmartExam(RewardTimeBean rewardTimeBean) {
        if(rewardTimeBean == null){
            showToast("智能练习玩手机奖励信息为空");
            return;
        }

        if(!rewardTimeBean.znlx){
            showToast("智能练习暂无题目");
            return;
        }

        Session.getSession().put("rewardTimeBean",rewardTimeBean);

        Intent intent = new Intent(this,ExamActivity.class);
        intent.putExtra("awardType",1);
        startActivityAllow(intent);
    }

    private void clearMainData() {
        if(timeAdapter != null && rewardTimeBeans != null){
            rewardTimeBeans.clear();
            timeAdapter.notifyDataSetChanged();

            llEmpty1.setVisibility(View.VISIBLE);
            LvTimeAward.setVisibility(View.GONE);
        }

        if(toyAdapter != null && rewardToyBeans != null){
            rewardToyBeans.clear();
            toyAdapter.notifyDataSetChanged();

            llEmpty2.setVisibility(View.VISIBLE);
            LvToyAward.setVisibility(View.GONE);
        }

        if(!ToolUtils.isListEmpty(fragmentList)){
            for (int i = 0;i < fragmentList.size();i++){
                SubjectFragment subjectFragment = fragmentList.get(i);
                if(subjectFragment != null){
                    Log.i(TAG,"subjectId=" + subjectFragment.getSubjectId());
                    SubjectRecyclerViewAdapter mSRVAdapter = subjectFragment.getmSRVAdapter();
                    if(mSRVAdapter == null){
                        Log.e(TAG,"mSRVAdapter == null");
                        continue;
                    }
                    List<LearnByDoBean> learnByDoList = mSRVAdapter.getLearnByDoList();
                    if(!ToolUtils.isListEmpty(learnByDoList)){
                        learnByDoList.clear();
                        mSRVAdapter.notifyDataSetChanged();

                        subjectFragment.clearUI();
                    }
                }
            }
        }
    }

    private class ChildChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG,"ChildChangeReceiver onReceive");

            ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
            if(currentChildBean == null){
                return;
            }

            currentChildText.setText(currentChildBean.childName);
            tvStarNum.setText(currentChildBean.stars + "");

            if(!TextUtils.isEmpty(currentChildBean.childAvatar)) {
                ivHeadPortrait.setVisibility(View.VISIBLE);
                ImageUtils.loadWXImageView(context, currentChildBean.childAvatar, ivHeadPortrait);
            }
            tvLevelTerm.setText(ToolUtils.getChildGradeStr(currentChildBean));

            getData(false);
        }
    }

    private void registerBroadcastReceiver() {
        LocalBroadcastManager localBroadcastManager= LocalBroadcastManager.getInstance(this);

        childChangeReceiver = new ChildChangeReceiver();
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(Constants.CHILD_CHANGE_RECEIVER_ACTION);
//        localBroadcastManager.registerReceiver(childChangeReceiver, intentFilter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == 100){
            getUserinfo(false);

            boolean permissionHasSet = SharedPreferencesUtils.getBooleanDate(Constants.MAIN_PERMISSION_HAS_SET_SHAREPREFERS_KEY);
            if(!permissionHasSet){
                startActivity(PermissionMainActivity.class);
            }

        }else if(resultCode == 200){
            showToast("兑换奖品成功");

            getUserinfo(true);
        }else if(resultCode == 300){
//            showToast("兑换奖品失败");
        }else if(resultCode == 400){//家长设置完成
            Log.i(TAG,"resultCode == 400 : 家长设置完成");
            getUserinfo(false);
        }else if(resultCode == 500){//玩具详情点击购买
            Session.getSession().put("maketingDataBean",maketingDataBean);

            startActivity(OpenVipActivity.class);
        }
    }

    public void getUserinfo(final boolean onlyStarChange) {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_USER_INFO);
        urlParse.putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if(userBean != null){
                            shuShanApplication.setUserBean(userBean);

                            if(!TextUtils.isEmpty(userBean.password)){
                                SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY,userBean.password);
                            }

                            List<ChildBean> childList = userBean.getChildList();
                            if(childList.size() > 0){
                                new ChildBeanDao(shuShanApplication).dropAndAddList(childList);
                            }else {
                                new ChildBeanDao(shuShanApplication.getInstance()).clearTab();
                            }

                            ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
                            if(currentChildBean != null){
                                if(onlyStarChange){
                                    tvStarNum.setText(currentChildBean.stars + "");
                                }else {
                                    currentChildText.setText(currentChildBean.childName);
                                    tvStarNum.setText(currentChildBean.stars + "");

                                    if(!TextUtils.isEmpty(currentChildBean.childAvatar)) {
                                        ivHeadPortrait.setVisibility(View.VISIBLE);
                                        ImageUtils.loadWXImageView(MainActivity.this, currentChildBean.childAvatar, ivHeadPortrait);
                                    }
                                    tvLevelTerm.setText(ToolUtils.getChildGradeStr(currentChildBean));
                                }
                            }

                            if(!onlyStarChange){
                                getData(false);
                            }

                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNoMsgError(netRetBean);
                    }
                });
    }

    public void getLoopUserinfo() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_USER_INFO);
        urlParse.putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        int currentId = shuShanApplication.getCurrentChildId();
                        if(currentId <= 0 || (!shuShanApplication.isVip())){
                            mHandler.sendEmptyMessageDelayed(0,DELAY_TIMES);
                        }

                    }

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if(userBean != null){
                            int currentId = shuShanApplication.getCurrentChildId();
                            if(currentId > 0 && shuShanApplication.isVip() && (!isFinishing()) && userBean.share_vip_last_time == 1){
                                showVipTimeEndDialog(userBean.activity_name);
                            }

                            shuShanApplication.setUserBean(userBean);

                            if(!TextUtils.isEmpty(userBean.password)){
                                SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY,userBean.password);
                            }

                            List<ChildBean> childList = userBean.getChildList();
                            if(childList.size() > 0){
                                new ChildBeanDao(shuShanApplication).dropAndAddList(childList);
                            }else {
                                new ChildBeanDao(shuShanApplication).clearTab();
                            }

                            ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
                            if(currentChildBean != null){
                                currentChildText.setText(currentChildBean.childName);
                                tvStarNum.setText(currentChildBean.stars + "");

                                if(!TextUtils.isEmpty(currentChildBean.childAvatar)) {
                                    ImageUtils.loadWXImageView(MainActivity.this, currentChildBean.childAvatar, ivHeadPortrait);
                                }
                                tvLevelTerm.setText(ToolUtils.getChildGradeStr(currentChildBean));
                            }

                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNoMsgError(netRetBean);
                    }
                });
    }

    private void gotoGoodsWebDetail(StarsDataBean starsDataBean) {
        if(starsDataBean == null){
            return;
        }

        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        UserBean currentUserBean = shuShanApplication.getUserBean();
        int childId = currentChildBean.id;
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.DIST_TOY_HTML)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("childid", (childId > 0) ? (childId+"") : "")
                .putValue("starsnum",currentChildBean.stars)
                .putValue("goodsid",starsDataBean.id)
                .putValue("viptype",ToolUtils.getVipTypeForGoodsDetails(currentUserBean))
                ;
        Log.i(TAG,"viptype = "+ToolUtils.getVipTypeForGoodsDetails(currentUserBean));
        Intent intent = new Intent(this, GoodsDetailWebActivity.class);
        intent.putExtra("title","奖品详情");
        intent.putExtra("url",urlParse.toString());
        startActivityForResultAllow(intent);
    }

    @Override
    public void onFragmentItemClick(View itemView, int position) {
        int childId = shuShanApplication.getCurrentChildId();
        if(childId <= 0){
            showGotoSetDialog();
        }else if(!shuShanApplication.isVip()){
            if(maketingActivityBean != null) {
                DialogUtil.showVIPpurchaseDialog(MainActivity.this, MainActivity.this, maketingActivityBean);
            }
        }

    }

    private void showGotoPermissionDialog() {
        if(permissionDialog == null){
            permissionDialog = new CustomDialog.Builder(this)
                    .setTitle("温馨提示")
                    .setMessage("发现您尚未完全设置权限，这将会导致控制不能稳定运行，是否去设置？")
                    .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    })
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            startActivity(PermissionMainActivity.class);

                        }
                    }).create();
        }

        if(!permissionDialog.isShowing()){
            permissionDialog.show();
        }
    }

    private void showGotoAccessibilityDialog() {
        if(permissionDialog == null){
            permissionDialog = new CustomDialog.Builder(this)
                    .setTitle("温馨提示")
                    .setMessage("发现您尚未完全设置权限，这将会导致控制不能稳定运行，开启辅助功能，将自动开启所有必须权限，是否去开启？")
                    .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    })
                    .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            startActivity(PermissionAccessibilityActivity.class);
//                            OpenAccessiSettingHelper.jumpToSettingPage(MainActivity.this);
                        }
                    }).create();
        }

        if(!permissionDialog.isShowing()){
            permissionDialog.show();
        }
    }

    private void showVipTimeEndDialog(String activityName) {
        if(vipTimeEndDialog == null){
            vipTimeEndDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            vipTimeEndDialog.setContentView(R.layout.dialog_vip_time_end);

            RelativeLayout rlBuyVip = vipTimeEndDialog.findViewById(R.id.rl_btn_buy_vip);
            rlBuyVip.setOnClickListener(this);
            RelativeLayout rlInvite = vipTimeEndDialog.findViewById(R.id.rl_btn_invite);
            rlInvite.setOnClickListener(this);
            if(!TextUtils.isEmpty(activityName)){
                TextView tvActivityName = vipTimeEndDialog.findViewById(R.id.tv_activity_name);
                tvActivityName.setText(activityName);
            }

            ImageView ivClose = vipTimeEndDialog.findViewById(R.id.iv_close_dialog);
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vipTimeEndDialog.dismiss();
                }
            });

            vipTimeEndDialog.setCancelable(false);
        }

        if(!vipTimeEndDialog.isShowing()){
            vipTimeEndDialog.show();
        }

    }

    private void showGotoSetDialog() {
        if(gotoSetDialog == null){
            gotoSetDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            gotoSetDialog.setContentView(R.layout.dialog_go_to_set);

            ImageView ivFork =  gotoSetDialog.findViewById(R.id.iv_fork);
            Button btnQuickSet =  gotoSetDialog.findViewById(R.id.btn_quick_set);
            Button btnGoRightNow =  gotoSetDialog.findViewById(R.id.btn_go_right_now);

            ivFork.setOnClickListener(this);
            btnQuickSet.setOnClickListener(this);
            btnGoRightNow.setOnClickListener(this);
            gotoSetDialog.setCancelable(false);
        }

        if(!gotoSetDialog.isShowing()){
            gotoSetDialog.show();
        }

    }

    private void showFloatDialog() {
        if(floatDialog == null){
            floatDialog = new CustomDialog.Builder(this)
                    .setTitle("温馨提示")
                    .setMessage("您的手机没有授予悬浮窗权限，请开启后再试")
                    .setNegativeButton("暂不开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();


                        }
                    })
                    .setPositiveButton("现在去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            OpenSettingUtils.openFloatManager(MainActivity.this);

                        }
                    }).create();
        }

        if(!floatDialog.isShowing()){
            floatDialog.show();
        }
    }

    private void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        if(tabStrip == null){
            return;
        }
        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    private void getUpdate() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.APP_VERSION);
        urlParse.putValue("system",Constants.OS_TYPE)
                .putValue("version", DeviceUtil.getVersionName(this));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UpdateBean>() {

                    @Override
                    protected void onSuccess(UpdateBean userBean) {
                        if(userBean != null){
                            showUpdateDialog(userBean);
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {

                    }

                });
    }

    private void showUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_dialog);
        updateDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);

        VerificationCodeView veriCodeView = updateDialog.findViewById(R.id.update_dialog_verification_code_view);
        veriCodeView.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onComplete(String content) {

                if(StringTools.pswValide(content)){
                    updateDialog.dismiss();

                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(MainActivity.this)//设置上下文
                            .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                            .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                            .setNotificationIconRes(R.drawable.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                            .setNotificationTitle("书山宝")//设置通知标题
                            .startDownLoad();//开始下载
                }else{
                    showToast("家长密码错误");
                }
            }
        });


        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });

        updateDialog.show();
    }

    private void logout() {
        if(TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
            startActivity(LoginOrRegisterActivity.class);
            return;
        }
        clickType = 3;
        DialogUtil.showParentLogoutDialog(this, this, this);
        closeDrawer();

        UmengEventUtil.onProfileSignOff();
    }

}
